package com.fujimana.android.manacode.converter;

import java.io.IOException;
import java.io.StreamTokenizer;

public class TokenAccessor {
	
	private StreamTokenizer tokenizer;
	
	private int count;

	public TokenAccessor(StreamTokenizer tokenizer) {
		this.tokenizer = tokenizer;
		this.count = 0;
	}

	public void cancel() {
		for(int i=0; i<this.count; i++) {
			pushBack();
		}
	}
	
	public void pushBack() {
		if(this.count > 0) {
			this.tokenizer.pushBack();
			this.count--;
		}
	}
	
	public String next() throws IOException {
		String word = null;
		
		switch (this.tokenizer.nextToken()) {
		case StreamTokenizer.TT_EOL:
			word = "\n";
			break;
		case StreamTokenizer.TT_WORD:
			word = tokenizer.sval;
			break;
		case TokenParser.QUOTE:
			word = "'" + tokenizer.sval + "'";
			break;
		case TokenParser.DOUBLE_QUOTE:
			word = '"' + tokenizer.sval + '"';
			break;
		default:
			word = "" + (char) tokenizer.ttype;
		}
		
		this.count++;
		
		return word;
	}
}
